import { useState, useEffect } from "react";

export function TypingEffect({ text, style, speed = 100, start = true, onComplete, onClick = e => { } }) {
  const [displayedText, setDisplayedText] = useState('');
  useEffect(() => {
    if (!start) return;

    let index = 0;
    function type() {
      if (text && index < text.length) {
        setDisplayedText(text.slice(0, index + 1));
        index++;
        setTimeout(type, speed);
      } else {
        if (onComplete) {
          onComplete();
        }
      }
    }
    type();
    return () => clearTimeout(type);
  }, [text, speed, start]);
  return <span style={style} onClick={onClick}>{displayedText}</span>;
}
